<template>
    <div style="margin-left: 2%;margin-right: 2%">
        <div style="margin-top: .8%;text-align: right">
            <el-button size="mini" type="warning"  @click="centerDialogVisible = true">添加用户</el-button>
        </div>
        <div style="margin-top: 7px;margin-bottom: 10px">

            <!--            v-loading="loading"-->
            <el-table
                    :data="userTable"
                    border
                    style="width: 100%">
                <el-table-column
                        prop="loginName"
                        min-width="209px"
                        label="账号"
                >
                </el-table-column>
                <el-table-column
                        prop="usersName"
                        min-width="209px"
                        label="用户姓名"
                >
                </el-table-column>
                <el-table-column
                        prop="roleName"
                        min-width="130px"
                        label="角色名称">
                </el-table-column>
                <el-table-column
                        width="120px"
                        label="操作"
                >
                    <template slot-scope="{$index,row}">
                        <!--            <el-tooltip placement="top" style="margin-left: 30%">-->
                        <!--              <div slot="content">删除</div>-->
                        <i  title="删除"  @click="delUser(row)" style="color: #e54e4e;margin-right: 20px" class="el-icon-delete-solid"></i>
                        <!--            </el-tooltip>-->
                        <!--            <el-tooltip placement="top" style="margin-left: 30%">-->
                        <!--              <div slot="content">重置密码</div>-->
                        <i      title="重置密码"  @click="confirmPassword(row)" style="color: #e54e4e" class="el-icon-key"></i>
                        <!--            </el-tooltip>-->
                    </template>
                </el-table-column>
            </el-table>

        </div>
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20, 50, 100, 200]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>



        <!--    添加用户-->
        <el-dialog
                title="添加用户"
                :visible.sync="centerDialogVisible"
                width="39%"
                center>
            <el-form ref="addUser" :rules="rules" :model="addUser" label-width="80px">
                <el-form-item label="角色名称" prop="roles">
                    <el-select   v-model="addUser.roles"  placeholder="请选择单位名称" >
                        <el-option label="采购管理员" value="2"></el-option>
                        <el-option label="采购员" value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item  label="账号" prop="loginName" >
                    <el-input  v-model="addUser.loginName" placeholder="请输入账号">
                    </el-input>
                </el-form-item>
                <el-form-item  label="密码"  prop="password" >
                    <el-input v-model="addUser.password" placeholder="请输入密码" show-password>
                    </el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="repeatPassword">
                    <el-input  v-model="addUser.repeatPassword" show-password placeholder="请确认密码"></el-input>
                </el-form-item>
                <el-form-item label="用户姓名" prop="userName">
                    <el-input  v-model="addUser.userName" placeholder="请确认用户姓名"></el-input>
                </el-form-item>
            </el-form>
            <div style="text-align: center">
                <el-button @click="cancelAddUser">取 消</el-button>
                <el-button type="primary" @click="submitUser">提 交</el-button>
            </div>
        </el-dialog>

        <!--    重置密码-->
        <el-dialog
                title="重置密码"
                :visible.sync="showReset"
                width="40%"
                center>
            <el-form ref="form"  :rules="rules" :model="resetPassword" label-width="120px">
                <el-form-item  prop="password" label="新的密码" >
                    <el-input v-model="resetPassword.password" show-password placeholder="请输入新的密码">
                    </el-input>
                </el-form-item>
                <el-form-item prop="repeatAPassword" label="确认密码" >
                    <el-input v-model="resetPassword.repeatAPassword" placeholder="请再次输入新的密码" show-password>
                    </el-input>
                </el-form-item>
            </el-form>
            <div style="text-align: center">
                <el-button @click="cancelReset">取 消</el-button>
                <el-button type="primary" @click="submitReset">提 交</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>


import {delOrgUser, getAllOrgUSer, OrgAddUser} from "@/api/shoppingManage/userManage";
import {reqResetPassword} from "@/api/sysUser";

export default {
    name: 'index',
    data(){
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.addUser.password) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }
        var validatePass1 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.resetPassword.password) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }
        return {
            rules:{
                loginName:[{required:true,message:'请输入账号',pattern: '[^ \x22]+',trigger:'blur'},{ min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur' }],
                userName:[{required:true,message:'请输入用户名',pattern: '[^ \x22]+',trigger:'blur'},{ min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur' }],
                roles:[{required:true,message:'请选择角色',trigger: ['blur','change']}],
                password:[{required:true,message:'请输入密码',pattern: '[^ \x22]+',trigger:'blur'},{ min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur' }],
                repeatPassword:[{required:true,validator: validatePass2,trigger:'blur'},{ min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur' }],
                repeatAPassword:[{required:true,validator: validatePass1,trigger:'blur'},{ min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur' }],
                nowPassword:[{required:true,message:'请输入当前密码',pattern: '[^ \x22]+',trigger:'blur'},{ min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur' }],
            },
            currentPage: 1,
            pageSize: 20,
            search:{
                unitName:'',
                userName:'',
                loginName:''
            },
            resetPassword:{
                password: "",
                repeatAPassword:'',
            },
            userId: JSON.parse(localStorage.getItem("userinfo")).userId,
            showReset:false,
            addUser: {
                roles: '',
                userName: '',
                loginName: '',
                password: '',
                repeatPassword:'',
            },
            showPageSearch:false,
            value:'',
            centerDialogVisible: false,
            total: 0,
            loading:true,
            userTable: [],
            loginName: "",
        }
    },
    mounted() {
        this.getGetUser()
    },
    methods:{
        handleSizeChange(val){
            this.pageSize = val
            this.getGetUser()
        },
        handleCurrentChange(val){
            this.currentPage = val
            this.getGetUser()
        },
        clearMes(){
            this.showPageSearch=false
            Object.keys(this.search).forEach(index=>this.search[index]='')
        },
        // 添加用户
        async submitUser(){
            this.$refs.addUser.validate(async (valid)=>{
                if (valid){
                    delete this.addUser.repeatPassword
                    let theData = {
                        roleId: this.addUser.roles,
                        usersName: this.addUser.userName,
                        loginName: this.addUser.loginName,
                        password: this.addUser.password
                    }
                    let res =await  OrgAddUser(theData)
                    if(res.data.code===200){
                        this.$message({
                            message: '添加成功',
                            type:'success'
                        });
                        this.addUser= {
                            roles: '',
                            userName: '',
                            loginName: '',
                            password: '',
                            repeatAPassword:'',
                            unitName:''
                        }
                        this.$refs["addUser"].resetFields();
                        await this.getGetUser()
                        this.centerDialogVisible=false
                    }else {
                        this.$message.error(res.data.msg)
                    }
                }else{
                    this.$message.error('请确保信息完整！')
                    return false;
                }
            })


        },
        // 获得用户
        async getGetUser(){
            this.loading=true
            let pageInfo = this.currentPage+ "/" + this.pageSize
            let res = await getAllOrgUSer(pageInfo)
            if (res){
                this.loading=false
            }
            if(res.data.code===200){
                this.userTable = res.data.data.record
                this.total=res.data.data.total
            }else {
                this.$message({
                    message: `${res.data.data.msg}`,
                    type:'warning'
                });
            }
        },
        // 重置密码
        submitReset(){
            this.$refs.form.validate(async (valid)=>{
                if (valid){
                    delete this.resetPassword.repeatAPassword
                    let theData={
                        loginName: this.loginName,
                        newPwd:this.resetPassword.password,
                    }
                    let res =await reqResetPassword(theData)
                    if(res.data.code===200){
                        this.$message({
                            type:'success',
                            message:'重置成功！！！'
                        })
                        this.$refs["form"].resetFields();
                        this.showReset=false
                    }else {
                        this.$message.error(res.data.msg)
                    }
                }
            })

        },
        cancelReset(){
            this.showReset=false
            Object.keys(this.resetPassword).forEach(index=>this.resetPassword[index]='')
            this.$message({
                message: '已取消操作',
            });
        },
        cancelAddUser(){
            this.$refs["addUser"].resetFields();
            this.centerDialogVisible =false
            this.addUser= {
                roles: '',
                userName: '',
                loginName: '',
                password: '',
                repeatAPassword:'',
                unitName:''
            }
            this.$message({
                message: '已取消操作',
            });

        },
        // 删除用户
        delUser(row){
            if (row.userId === this.userId) {
                this.$message('当前账号！不能删除');
            } else {
                this.$confirm('确认删除该用户吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    let res = await delOrgUser(row.userId)
                    if (res.data.code === 200) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        await this.getGetUser()
                    } else {
                        this.$message.error(res.data.msg)
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        },
        // 打开重置窗口
        confirmPassword(row){
            if (this.userId === row.userId){
                this.$message('当前账号！不能重置密码');
            }else {
                this.resetPassword.password = ''
                this.resetPassword.nowPassword = ''
                this.resetPassword.repeatAPassword = ''
                // 设置loginName
                this.loginName = row.loginName
                this.showReset = true
            }
        },
        open() {
            this.$confirm('此操作将永久删除选中的单位信息, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },


    }
}
</script>

<style scoped>

</style>
<style>
.el-tag + .el-tag {
    margin-left: 10px;
}
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}
.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>
